<?php

namespace Admin\Controller;

use Admin\Library\Weixin;

/**
 * 文化日历
 *
 * Class EventController
 * @package Admin\Controller
 */
class EventController extends PublicController
{
    private $model;

    public function _initialize()
    {
        $this->model = M('Event');
        $this->assign('modules', '文化日历');
    }

    /**
     * 文化日历列表
     */
    public function index()
    {
        $this->assign('title', '活动列表');
        $where = "is_del=0";
        if (isset($_GET['keyword'])) {
            $where .= " AND title like '%" . trim($_GET['keyword']) . "%'";
            $this->assign('keyword', trim($_GET['keyword']));
        }
        $count = $this->model->where($where)->count();
        $perPage = 20;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        $totalPage = ceil($count / $perPage);
        $pageObj = $this->page_index($count, $totalPage, $page);
        $list = $this->model->where($where)->order('sort = 0, sort asc, id desc')->limit($page * $perPage, $perPage)->select();

        $this->assign('list', $list);
        $this->assign('pageObj', $pageObj);
        $this->display();
    }

    /**
     * 文化日历编辑页面
     */
    public function add()
    {
        $this->assign('title', '添加活动');

        if (isset($_GET['id'])) {
            $detail = $this->model->where(['id' => intval($_GET['id']), 'is_del' => 0])->find();
            if (!empty($detail)) {
                $this->assign('title', '修改活动');
                $this->assign("detail", $detail);
            }
        }

        $this->display();
    }

    /**
     * 保存文化日历内容
     */
    public function save()
    {
        $postData = array(
            'title'          => $_POST['title'],
            'content'        => $_POST['content'],
            'start_date'     => $_POST['start_date'],
            'end_date'       => $_POST['end_date'],
            'business_hours' => $_POST['business_hours'],
            'tel'            => $_POST['tel'],
            'address'        => $_POST['address'],
            'price'          => empty($_POST['price']) ? 0 : floatval($_POST['price']),
            'total'          => empty($_POST['total']) ? 0 : intval($_POST['total']),
            'sort'           => empty($_POST['sort']) ? 0 : intval($_POST['sort']),
            'status'         => $_POST['status'],
        );
        //上传图片
        if (!empty($_FILES["file"]["tmp_name"])) {
            $info = $this->upload_images($_FILES["file"], array('jpg', 'png', 'jpeg'), 'event/' . date('Ymd'));
            if (!is_array($info)) {
                $this->error($info);
            } else {
                $postData['cover'] = 'UploadFiles/' . $info['savepath'] . $info['savename'];
            }
        }

        if (isset($_POST['id']) && !empty($_POST['id'])) {
            $id = intval($_POST['id']);
            $result = $this->model->where('id=' . $id)->save($postData);
        } else {
            $postData['create_at'] = date('Y-m-d H:i:s');
            $postData['remain'] = $postData['total'];
            $result = $this->model->add($postData);
        }

        if ($result) {
            $this->success('操作成功.', U('index'));
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 删除文化日历
     */
    public function del()
    {
        $id = intval($_REQUEST['did']);
        $info = $this->model->where('id=' . $id)->find();
        if (!$info) {
            $this->error('信息错误.');
            exit();
        }

        if (intval($info['del']) == 1) {
            $this->success('操作成功！.');
            exit();
        }

        $result = $this->model->where('id=' . $id)->save(['is_del' => 1]);
        if ($result) {
            $this->redirect('index');
        } else {
            $this->error('操作失败.');
        }
    }

    /**
     * 预约报名列表
     */
    public function apply()
    {
        $this->assign('title', '预约报名管理');
        $where = "1=1";
        if (isset($_GET['event_id']) && $eventId = intval($_GET['event_id'])) {
            $where .= " AND event_id = {$eventId}";
            $this->assign('event_id', $eventId);
        }
        if(isset($_GET['s_id'])) {
           switch ($_GET['s_id']){
               case 1:
                   $where .= " AND mobile like '%" . trim($_GET['keyword']) . "%'";
                   break;
               case 2:
                   $wh = "status=1 AND  title like '%" . trim($_GET['keyword']) . "%'";
                   $ids = M("event")->where($wh)->getField("id");
                   $where .= " AND event_id = {$ids}";
                   break;
               case 3:
                   $where .= " AND name like '%" . trim($_GET['keyword']) . "%'";
                   break;
           }
            $this->assign('keyword', trim($_GET['keyword']));
            $this->assign('s_id', $_GET['s_id']);
        } else {
            $this->assign('s_id', 0);
        }
        //获取活动列表
        $event = $this->model->where('is_del=0')->field("id,title")->select();
        $count = M('event_apply')->where($where)->count();
        $perPage = 20;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        $totalPage = ceil($count / $perPage);
        $pageObj = $this->page_index($count, $totalPage, $page);
        $list = M('event_apply')->join('lr_event on lr_event.id = lr_event_apply.event_id')->field('lr_event_apply.*, lr_event.title')->where($where)->order('apply_status asc, id desc')->limit($page * $perPage, $perPage)->select();

        $this->assign('list', $list);
        $this->assign("event",$event);
        $this->assign('pageObj', $pageObj);
        $this->display();
    }

    /**
     * 预约审核通过
     */
    function applySuc()
    {
        $id = intval($_POST['id']);
        if (empty($id)) {
            $this->error('操作失败sdv.');
        }
        $info = M('event_apply')->where('id=' . $id)->find();
        if (!$info) {
            $this->error('信息错误.');
        }

        if (intval($info['apply_status']) == 2) {
            $this->success('操作成功！.');
        }
        $ff = $this->model->where("id=".$info['event_id'])->find();
        if ($ff['total']>0) {
            if ( $ff['remain']==0) {
                $this->error('票数已发完！');
                exit;
            }
            // 审核通过后更新活动报名人数
            $this->model->where("id = {$info['event_id']}")->setDec('remain',1);
        }
        $result = M('event_apply')->where('id=' . $id)->save(['apply_status' => 2,'apply_remark'=>$_POST['apply_remark']]);
        // 发送模板消息
        $openId = M('user')->where(['id' => $info['user_id']])->getField('openid');
        if ($openId) {
            $eventInfo = M('event')->where(['id' => $info['event_id']])->find();
            if (!empty($eventInfo)) {
                $wenxin = new Weixin();
                $wenxin::templateSend($openId, 'iofbLuEmwDW6jXiGfVMpvE1J_LYEWe2sAibXrKDi4oE', 'pages/user_conter/user_conter', $info['form_id'], [
                    'keyword1' => $eventInfo['title'],
                    'keyword2' => $eventInfo['address'],
                    'keyword3' => $eventInfo['start_date'] . '至' . $eventInfo['end_date'] . ' ' . $eventInfo['business_hours'],
                    'keyword4' => $eventInfo['tel'],
                    'keyword5' => '报名成功，请准时参加',
                ]);
            }
        }
        if ($result) {
            exit(json_encode(array('done' => true, 'msg' => '回复提交成功')));
        } else {
            exit(json_encode(array('done' => false, 'msg' => '数据保存错误')));
        }
    }

    /**
     * 预约审核被拒绝
     */
    public function applyFail()
    {
        if (empty($_POST['id']) || empty(($_POST['apply_remark']))) {
            exit(json_encode(array('done' => false, 'msg' => '请输入拒绝原因')));
        }
        $data = [
            'apply_remark' => $_POST['apply_remark'],
            'apply_status' => 3
        ];

        $result = M('event_apply')->where(['id' => intval($_POST['id'])])->save($data);
        if ($result) {
            exit(json_encode(array('done' => true, 'msg' => '回复提交成功')));
        } else {
            exit(json_encode(array('done' => false, 'msg' => '数据保存错误')));
        }
    }

    /**
     * 导出通过人的名单
     */
    public function export()
    {
        vendor("PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.Writer.Excel5");
        $where = '1=1';
        if (empty($_POST['event_id'])) {
            $where .= '';
        } else {
            $where .= " AND event_id='".$_POST['event_id']."'";
        }
        if (empty($_POST['apply_status'])) {
            $where .= '';
        } else {
            $where .= " AND apply_status='".$_POST['apply_status']."'";
        }
        if(isset($_POST['s_id'])) {
            switch ($_POST['s_id']){
                case 1:
                    $where .= " AND mobile like '%" . trim($_POST['u_name']) . "%'";
                    break;
                case 3:
                    $where .= " AND name like '%" . trim($_POST['u_name']) . "%'";
                    break;
            }

        }
        $event_list = M('event_apply')->where($where)->select();
        $excelObject = new \PHPExcel();
        $excelObject->setActiveSheetIndex(0)
            ->setCellValue('A1', '编号')
            ->setCellValue('B1', '姓名')
            ->setCellValue('C1', '手机')
            ->setCellValue('D1', '人数')
            ->setCellValue('E1', '活动')
            ->setCellValue('F1', '状态');
        $rowIndex=2;
        foreach ($event_list as  $k => $row) {
            switch ($row['apply_status']){
                case 1:
                    $status = "申请中";
                    break;
                case 2:
                    $status = "通过";
                    break;
                case 3:
                    $status = "拒接";
                    break;
            }
            $title = $this->model->where("id=".$row['event_id'])->getField("title");
            $excelObject->getActiveSheet()
                ->setCellValueExplicit('A' . $rowIndex, (string)$row['id'])
                ->setCellValue('B' . $rowIndex, $row['name'])
                ->setCellValue('C' . $rowIndex, $row['mobile'])
                ->setCellValueExplicit('D' . $rowIndex, $row['number'])
                ->setCellValue('E' . $rowIndex, $title)
                ->setCellValue('F' . $rowIndex, $status);
            $rowIndex++;
            $name = $title;
        }
        $title = date('Y-m-d')."-".$name.'-名单列表';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $title . '.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');

        $objWriter = new \PHPExcel_Writer_Excel5($excelObject);
        $objWriter->save('php://output');
    }
}